package com.yss.reportworld.service.impl;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yss.common.core.enums.YssStatusEnum;
import com.yss.common.core.exception.BusinessException;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.security.utils.DictUtils;
import com.yss.reportworld.domain.Table;
import com.yss.reportworld.domain.TableDetail;
import com.yss.reportworld.enums.ReportWorldEnum;
import com.yss.reportworld.service.ITableService;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yss.reportworld.service.ITableDetailStandardCheckService;
import com.yss.reportworld.mapper.TableDetailStandardCheckMapper;
import com.yss.reportworld.domain.TableDetailStandardCheck;
import org.springframework.util.CollectionUtils;

/**
 * 字段校验规则Service业务层处理
 *
 * @author yss
 * @date 2023-03-30
 */
@Slf4j
@Service
public class TableDetailStandardCheckServiceImpl extends ServiceImpl<TableDetailStandardCheckMapper, TableDetailStandardCheck> implements ITableDetailStandardCheckService {
    @Autowired
    private ITableService tableService;

    /**
     * 查询字段校验规则列表
     *
     * @param tableDetailStandardCheck 字段校验规则
     * @return 字段校验规则
     */
    @Override
    public List<TableDetailStandardCheck> selectTableDetailStandardCheckList(TableDetailStandardCheck tableDetailStandardCheck) {
        QueryWrapper<TableDetailStandardCheck> wrapper = new QueryWrapper();
        wrapper.orderByDesc("STATUS");
        if (null == tableDetailStandardCheck) {
            return this.list(wrapper);
        }
        if (StringUtils.isNotEmpty(tableDetailStandardCheck.getColumnName())) {
            wrapper.eq("COLUMN_NAME", tableDetailStandardCheck.getColumnName());
        }
        if (null != tableDetailStandardCheck.getStatus()) {
            wrapper.eq("STATUS", tableDetailStandardCheck.getStatus());
        }
        // 导出的时候选择了数据，按照选择的数据
        if (StringUtils.isNotEmpty(tableDetailStandardCheck.getIds())) {
            List<String> list = JSONArray.parseArray(tableDetailStandardCheck.getIds(), String.class);
            if(StringUtils.isNotEmpty(list)) {
                wrapper.in("ID", list);
            }
        }
        return this.list(wrapper);
    }


    /**
     * 表字段的时候检验字段规范
     *
     * @return
     * @throws Exception
     */
    public void tableDetailStandardCheckInfo(TableDetail tableDetail) {
        if (null == tableDetail || StringUtils.isEmpty(tableDetail.getColumnName())) {
            log.error("没有获取到要检查的表字段信息！");
            return;
        }
        QueryWrapper<TableDetailStandardCheck> wrapper = new QueryWrapper<>();
        wrapper.eq("STATUS", YssStatusEnum.NORMAL.getCode());
        List<TableDetailStandardCheck> list = this.list(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            log.info("没有获取到字段的检验规则信息！");
            return;
        }
        StringBuffer msg = new StringBuffer();
        if (StringUtils.isEmpty(tableDetail.getColumnChineseName())) {
            // throw new BusinessException(tableDetail.getColumnName() + "字段没有中文注释");
            msg.append(tableDetail.getColumnName() + "字段没有中文注释").append("\r\n");
        }
        //字段类型
        Map<String, String> mapColumnType = DictUtils.getDictCacheMap(ReportWorldEnum.COLUMN_TYPE.getCode());
        for (TableDetailStandardCheck check : list) {
            if (null == check || StringUtils.isEmpty(check.getColumnName())) {
                continue;
            }
            // 中文名称相同的字段名称比较
            if (StringUtils.isNotBlank(check.getColumnChineseName()) && StringUtils.isNotBlank(tableDetail.getColumnChineseName())
                    && tableDetail.getColumnChineseName().equals(check.getColumnChineseName())
                    && !tableDetail.getColumnName().equals(check.getColumnName())) {
                //throw new BusinessException("中文注释为【" + check.getColumnChineseName() + "】按照规范字段名称应该是【" + check.getColumnName() + "】");
                msg.append("中文注释为【" + check.getColumnChineseName() + "】按照规范字段名称应该是【" + check.getColumnName() + "】").append("\r\n");
            }
            if (!tableDetail.getColumnName().equals(check.getColumnName())) {
                continue;
            }
            // 中文名称
            if ((StringUtils.isNotBlank(check.getColumnChineseName()) && StringUtils.isEmpty(tableDetail.getColumnChineseName())) ||
                    (StringUtils.isNotBlank(check.getColumnChineseName()) && StringUtils.isNotBlank(tableDetail.getColumnChineseName())
                            && !tableDetail.getColumnChineseName().equals(check.getColumnChineseName()))) {
                // throw new BusinessException(tableDetail.getColumnName() + "字段的中文注释按照规范应该为【" + check.getColumnChineseName() + "】");
                msg.append("字段【" + tableDetail.getColumnName() + "】字段的中文注释按照规范应该为【" + check.getColumnChineseName() + "】").append("\r\n");
            }
            // 字段类型
            if ((null != check.getColumnType() && null == tableDetail.getColumnType()) ||
                    (null != check.getColumnType() && null != tableDetail.getColumnType()
                            && tableDetail.getColumnType().intValue() != check.getColumnType().intValue())) {
                // throw new BusinessException(tableDetail.getColumnName() + "字段类型应该为【" /*+ mapColumnType.get(String.valueOf(check.getColumnType()))*/ + "】");
                msg.append("字段【" + tableDetail.getColumnName() + "】字段类型应该为【" + mapColumnType.get(String.valueOf(check.getColumnType())) + "】").append("\r\n");
            }
            // 字段长度
            if ((null != check.getColumnLength() && null == tableDetail.getColumnLength()) ||
                    (null != check.getColumnLength() && null != tableDetail.getColumnLength()
                            && tableDetail.getColumnLength().intValue() != check.getColumnLength().intValue())) {
                // throw new BusinessException(tableDetail.getColumnName() + "字段长度应该为【" + check.getColumnLength() + "】");
                msg.append("字段【" + tableDetail.getColumnName() + "】字段长度应该为【" + check.getColumnLength() + "】").append("\r\n");
            }
            // 小数位数
            if ((null != check.getColumnDecimal() && null == tableDetail.getColumnDecimal()) ||
                    (null != check.getColumnDecimal() && null != tableDetail.getColumnDecimal()
                            && tableDetail.getColumnDecimal().intValue() != check.getColumnDecimal().intValue())) {
                // throw new BusinessException(tableDetail.getColumnName() + "字段小数应该为【" + check.getColumnDecimal() + "】");
                msg.append("字段【" + tableDetail.getColumnName() + "】字段小数应该为【" + check.getColumnDecimal() + "】").append("\r\n");
            }
            // 是否主键
            if ((null != check.getPrimaryKey() && null == tableDetail.getPrimaryKey()) ||
                    (null != check.getPrimaryKey() && null != tableDetail.getPrimaryKey()
                            && tableDetail.getPrimaryKey().intValue() != check.getPrimaryKey().intValue())) {
                // throw new BusinessException(tableDetail.getColumnName() + (1 == check.getPrimaryKey() ? "应该是主键" : "不能为主键"));
                msg.append(tableDetail.getColumnName() + (1 == check.getPrimaryKey() ? "应该是主键" : "不能为主键")).append("\r\n");
            }
            // 是否可为空
            if ((null != check.getColumnNull() && null == tableDetail.getColumnNull()) ||
                    (null != check.getColumnNull() && null != tableDetail.getColumnNull()
                            && tableDetail.getColumnNull().intValue() != check.getColumnNull().intValue())) {
                //throw new BusinessException(tableDetail.getColumnName() + (1 == check.getColumnNull() ? "应该为空" : "不能为空"));
                msg.append(tableDetail.getColumnName() + (1 == check.getColumnNull() ? "应该为空" : "不能为空")).append("\r\n");
            }
            // 默认值
            if ((StringUtils.isNotBlank(check.getColumnDefault()) && StringUtils.isEmpty(tableDetail.getColumnDefault())) ||
                    StringUtils.isNotBlank(check.getColumnDefault()) && StringUtils.isNotBlank(tableDetail.getColumnDefault())
                            && !tableDetail.getColumnDefault().toUpperCase().equals(check.getColumnDefault().toUpperCase())) {
                msg.append("字段【" + check.getColumnName() + "】默认值应该为：" + check.getColumnDefault()).append("\r\n");
            }
        }
        if (StringUtils.isNotEmpty(msg)) {
            QueryWrapper<Table> wrapperTable = new QueryWrapper();
            wrapperTable.eq("ID", tableDetail.getTableId());
            Table table = tableService.getOne(wrapperTable);
            msg.insert(0, "表【" + table.getName() + "】校验不通过：");
            throw new BusinessException(msg.toString());
        }
    }
}
